﻿using Appliaction.Dto.DB;
using Appliaction.IAppServices.DB;
using AutoMapper;
using Domain.Entitys.DB;
using EFCore;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace API.Controllers.DB
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class Db_AttachmetController : ControllerBase
    {
        private readonly IDb_AttachmentService db_AttachmentService;
        private readonly IMapper mapper;
        private readonly IWebHostEnvironment webHostEnvironment;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly MyDbContext myDbContext;

        public Db_AttachmetController(IDb_AttachmentService db_AttachmentService, IMapper mapper, IWebHostEnvironment webHostEnvironment, IHttpContextAccessor httpContextAccessor,
            MyDbContext myDbContext)
        {
            this.db_AttachmentService = db_AttachmentService;
            this.mapper = mapper;
            this.webHostEnvironment = webHostEnvironment;
            this.httpContextAccessor = httpContextAccessor;
            this.myDbContext = myDbContext;
        }

        /// <summary>
        /// 添加附件信息
        /// </summary>
        /// <param name="attachmentFileAddDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> AttachmetAddAsync(Db_AttachmentFileAddDto attachmentFileAddDto)
        {
            return new JsonResult(await db_AttachmentService.AttachmetAddAsync(attachmentFileAddDto));
        }

        /// <summary>
        /// 保存图片并返回图片的名称、地址、大小
        /// </summary>
        /// <param name="formFiles"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UploadMultipleAvatars(IFormFileCollection formFiles)
        {
            // 检查是否有文件上传
            if (formFiles == null || formFiles.Count == 0)
                return new JsonResult(new { success = false, message = "未选择文件" });

            try
            {
                // 1. 获取项目根目录
                string contentRoot = webHostEnvironment.ContentRootPath;
                string imageFolder = Path.Combine(contentRoot, "Image");

                var httpContext = httpContextAccessor.HttpContext;
                if (httpContext == null)
                {
                    return new JsonResult("无法获取HTTP上下文");
                }
                string scheme = httpContext.Request.Scheme;//http或https
                string host = httpContext.Request.Host.ToString();
                string baseUrl = $"{scheme}://{host}";
                // 确保文件夹存在
                if (!Directory.Exists(imageFolder))
                {
                    Directory.CreateDirectory(imageFolder);
                }

                // 存储上传成功的文件信息
                var uploadedPaths = new List<string>();
                var fileNames = new List<string>();
                var fileSizes = new List<long>();
                var fileTypes = new List<string>(); // 新增：存储文件类型

                // 2. 循环处理每个文件
                foreach (var formFile in formFiles)
                {
                    // 获取文件扩展名
                    var fileExtension = Path.GetExtension(formFile.FileName).ToLower();
                    var mimeType = formFile.ContentType; // 例如 "image/jpeg"
                    // 生成唯一文件名
                    var newFileName = $"{Guid.NewGuid()}{fileExtension}";
                    var filePath = Path.Combine(imageFolder, newFileName);
                    var relativePath = baseUrl + "/Image/" + newFileName; // 假设Img是Web访问路径前缀

                    // 保存文件
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(fileStream);
                    }

                    // 记录成功上传的信息
                    uploadedPaths.Add(relativePath);
                    fileNames.Add(newFileName);
                    fileSizes.Add(formFile.Length);
                    fileTypes.Add(mimeType); // 添加文件类型
                }

                // 返回所有上传成功的信息
                return new JsonResult(new
                {
                    fileName = fileNames,
                    paths = uploadedPaths,
                    fileSize = fileSizes,
                    fileType = fileTypes // 返回文件类型
                });
            }
            catch (Exception ex)
            {
                return new JsonResult(new { success = false, message = $"上传失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 根据编号查询对应的附件信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetDb_AttachmentsAsync(string code)
        {
            return new JsonResult(await db_AttachmentService.GetDb_AttachmentsAsync(code));
        }

        /// <summary>
        /// 删除编号对应公共附件信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult Attachmetdel(string code)
        {
            return new JsonResult(db_AttachmentService.Attachmetdel(code));
        }
    }
}
